﻿Imports MultiPlug.Plugins
Imports WeifenLuo.WinFormsUI.Docking

Public Class StartForm
    Implements IMessageFilter

    Private _pluginHandler As PluginHandler

    Private _logger As log4net.ILog

    Private WithEvents _transaktionDisplayTimer As System.Windows.Forms.Timer

    Public Const WINDOW_SAVE_PATH_KEY As String = "windowStateFile"

    Public Const PROGRAM_TEXT As String = "MultiPlug"

    Private WithEvents _serviceManager As LibMultiPlug.Core.Services.ServiceManager

    Private _console As LibMultiPlug.Core.Console.MultiPlugConsole

    Private Const WM_KEYDOWN As Integer = &H100

    Public Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

        Application.AddMessageFilter(Me)


        Call InternalInitialize()
    End Sub


    Public Sub InternalInitialize()

        _logger = log4net.LogManager.GetLogger(GetType(StartForm))

        _serviceManager = LibMultiPlug.Core.Services.ServiceManager.GetInstance()

        _serviceManager.GetBenachrichtigungsService()

        LibMultiPlug.Core.Statusmeldungen.Statusmeldungscontroller.SetToolStripStatusLabel(ToolStripStatusLabel1)

        AusgabeForm.Show(MainDockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockBottom)

        ' den pluginhandler laden
        _pluginHandler = New PluginHandler
        _pluginHandler.LoadPlugins(Me.MainDockPanel, _
                                   LibMultiPlug.Core.Services.ServiceManager.GetInstance(), _
                                   LibMultiPlug.Core.Services.ServiceManager.GetInstance().GetRootDbDataService())

        If _logger.IsDebugEnabled Then _logger.Debug("Plugins geladen...")

        _pluginHandler.SetPlugins(ModuleToolStripMenuItem, ToolStripContainer1, SymbolleistenToolStripMenuItem)

        If _logger.IsDebugEnabled Then _logger.DebugFormat("Plugins im {0} untergebracht...", Me.GetType().ToString())

        ' den timer für die transaktionsmarkierung initialisieren
        _transaktionDisplayTimer = New System.Windows.Forms.Timer
        _transaktionDisplayTimer.Interval = 500

        ' die sichtbarkeit der buttons steuern
        Call SetDefaultButtons()


        BenachrichtigungForm.Show(MainDockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockBottom)


        ' laden der der toolbarpositionen
        System.Windows.Forms.ToolStripManager.LoadSettings(Me)

        ' den eventhandler für das hinzufügen einer neuen benachrichtigung zuordnen
        AddHandler LibMultiPlug.Core.Benachrichtigungen.BenachrichtigungsManager.GetInstance().BenachrichtigungAdded, _
            Sub(message As LibMultiPlug.Core.Benachrichtigungen.Benachrichtigung)
                Dim bf As New BenachrichtigungPopupForm
                bf.Show(message)
            End Sub

        AddHandler _serviceManager.GetReportingService.ReportChanged, Sub()
                                                                          ReportsToolStripMenuItem.DropDownItems.Clear()
                                                                          For Each rle As LibMultiPlug.Core.Reporting.ReportListEntry In _serviceManager.GetReportingService.GetReportsForList()
                                                                              Dim reportEntry As New ToolStripMenuItem
                                                                              reportEntry.Text = rle.Name
                                                                              reportEntry.Name = rle.Id.ToString()
                                                                              AddHandler reportEntry.Click, Sub(sender As Object, e As EventArgs)
                                                                                                                Dim rf As New Forms.ReportForm
                                                                                                                rf.Show(MainDockPanel, CInt(sender.Name))
                                                                                                            End Sub
                                                                              reportEntry.Image = My.Resources.database_lightning
                                                                              ReportsToolStripMenuItem.DropDownItems.Add(reportEntry)
                                                                          Next
                                                                      End Sub

        _serviceManager.GetReportingService.RaiseReportChangedEvent()

        Forms.Plugins.PluginNavigationForm.Show(MainDockPanel, DockState.DockLeftAutoHide)
        ' den pluginbaum mit anzeigen
        ' Forms.Plugins.PluginNavigationForm.Show(MainDockPanel, DockState.DockLeftAutoHide)

        ' das transaktionfenster in den fokus (immer zum schluss)
        tbTransaktion.Focus()

        'ReportEditForm.Show(MainDockPanel)
    End Sub


    Private Sub tbTransaktion_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbTransaktion.KeyDown

        If e.KeyCode = Keys.Enter Then
            InternalStartTransaktion(tbTransaktion.Text)
        End If

    End Sub


    Private Sub tbStartTransaktion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartTransaktion.Click
        InternalStartTransaktion(tbTransaktion.Text)
    End Sub


    Private Sub InternalStartTransaktion(ByVal transaktionText As String)
        Try
            Dim argsList As New List(Of String)(transaktionText.Split(":"))
            Dim transactionName As String = argsList(0)
            argsList.RemoveAt(0)
            Dim args() As String = argsList.ToArray()

            If _pluginHandler.StartTransaktion(transactionName, args) Then
                tbTransaktion.BackColor = Color.LightGreen
            Else
                tbTransaktion.BackColor = Color.LightCoral
            End If

            Me.Refresh()

            _transaktionDisplayTimer.Start()
        Catch ex As Exception
            _logger.Error(ex.Message, ex)
            MessageBox.Show(ex.Message, "Fehler beim Transaktionsaufruf", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    Private Sub _transaktionDisplayTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles _transaktionDisplayTimer.Tick

        tbTransaktion.Clear()
        tbTransaktion.ResetBackColor()
        _transaktionDisplayTimer.Stop()

    End Sub


    Private Sub MainDockPanel_ActiveContentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MainDockPanel.ActiveContentChanged

        If MainDockPanel.ActiveContent IsNot Nothing AndAlso _
           TypeOf MainDockPanel.ActiveContent Is WeifenLuo.WinFormsUI.Docking.DockContent Then

            Me.Text = String.Format("{0} - {1}", PROGRAM_TEXT, CType(MainDockPanel.ActiveContent,  _
                                    WeifenLuo.WinFormsUI.Docking.DockContent).Text)

        Else
            Me.Text = PROGRAM_TEXT
        End If

        Try

            Call SetDefaultButtons()

            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then
                AddHandler CType(MainDockPanel.ActiveContent,  _
                                 LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).OptionsChanged, Sub()
                                                                                                        Call SetDefaultButtons()
                                                                                                    End Sub
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try


    End Sub


    Private Sub SetDefaultButtons()

        Dim activeContent As LibMultiPlug.Core.Plugins.Interfaces.IFormOptions

        If MainDockPanel.ActiveContent IsNot Nothing AndAlso _
            TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then

            activeContent = MainDockPanel.ActiveContent

        Else

            activeContent = New LibMultiPlug.Core.Plugins.EmptyFormOptions()

        End If

        '
        ' Die aktionen für den StandardToolStrip zuordnen
        '
        tsbNew.Enabled = activeContent.SetNew

        tsbOpen.Enabled = activeContent.SetOpen

        tsbSave.Enabled = activeContent.SetSave

        tsbPrint.Enabled = activeContent.SetPrint

        tsbPagePreview.Enabled = activeContent.SetPagePreview

        tsbDelete.Enabled = activeContent.SetDelete

        tsbRefresh.Enabled = activeContent.SetRefresh

        '
        ' Die Aktionen für die MenuButtons zuordnen
        '
        NeuToolStripMenuItem.Enabled = activeContent.SetNew

        ÖffnenToolStripMenuItem.Enabled = activeContent.SetOpen

        SpeichernToolStripMenuItem.Enabled = activeContent.SetSave

        SpeichernunterToolStripMenuItem.Enabled = activeContent.SetSaveAs

        DruckenToolStripMenuItem.Enabled = activeContent.SetPrint

        SeitenansichtToolStripMenuItem.Enabled = activeContent.SetPagePreview

    End Sub

#Region "StandardToolbar EventHandler"

    Private Sub NewEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbNew.Click, NeuToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).[New]()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub OpenEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbOpen.Click, ÖffnenToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).Open()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub SaveEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbSave.Click, SpeichernToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).Save()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub SaveAsEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles SpeichernunterToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).SaveAs()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub PrintEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbPrint.Click, DruckenToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).Print()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub PagePreviewEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbPagePreview.Click, SeitenansichtToolStripMenuItem.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).PagePreview()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub DeleteEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbDelete.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).Delete()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

    Private Sub RefreshEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles tsbRefresh.Click
        Try
            If TypeOf MainDockPanel.ActiveContent Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions Then _
                CType(MainDockPanel.ActiveContent,  _
                    LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).Refresh()
        Catch niex As NotImplementedException
            MessageBox.Show("Dies Funktion ist für dieses Formular nicht implementiert.")
        End Try
    End Sub

#End Region



    Private Sub StandardToolStripMenuItem_CheckStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StandardToolStripMenuItem.CheckStateChanged
        tsStandard.Visible = StandardToolStripMenuItem.Checked
    End Sub


    Private Sub TransaktionToolStripMenuItem_CheckStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransaktionToolStripMenuItem.CheckStateChanged
        tsTransaktion.Visible = TransaktionToolStripMenuItem.Checked
    End Sub


    Private Sub BeendenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BeendenToolStripMenuItem.Click
        End
    End Sub


    Private Sub AusgabefensterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AusgabefensterToolStripMenuItem.Click
        AusgabeForm.Show(MainDockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockBottom)
    End Sub


    Private Sub FensterpositionenSpeichernToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FensterpositionenSpeichernToolStripMenuItem.Click

        System.Windows.Forms.ToolStripManager.SaveSettings(Me)

    End Sub


    Private Sub MainDockPanel_ContentAdded(ByVal sender As System.Object, ByVal e As WeifenLuo.WinFormsUI.Docking.DockContentEventArgs) Handles MainDockPanel.ContentAdded

        Try

            If TypeOf e.Content Is LibMultiPlug.Core.Plugins.Interfaces.IFormOptions AndAlso _
                CType(e.Content, LibMultiPlug.Core.Plugins.Interfaces.IFormOptions).SetCoopDesign Then

                CoorpDesignLib.ControlFormater.GetInstance().RegisterControls(CType(e.Content, WeifenLuo.WinFormsUI.Docking.DockContent).Controls)

            End If
        Catch ex As InvalidCastException
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub BenachrichtigungenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BenachrichtigungenToolStripMenuItem.Click
        BenachrichtigungForm.Show(MainDockPanel, DockState.DockBottom)
    End Sub


    Private Sub PluginbaumToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PluginbaumToolStripMenuItem.Click
        Forms.Plugins.PluginNavigationForm.Show(MainDockPanel, DockState.DockLeft)
    End Sub

    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        If m.Msg = WM_KEYDOWN Then
            If m.WParam.ToString() = "220" Then
                ' Taste ^
                _console.SetVisibility(Not _console.GetVisibility())
                Return True
            Else
                ' Erlaube das scrollen in der Konsole nur wenn die Konsole sichtbar ist
                If _console.GetVisibility() = True Then
                    If m.WParam.ToString() = "33" Then
                        ' Bildhoch
                        _console.Scroll_Up()
                        Return True
                    ElseIf m.WParam.ToString() = "34" Then
                        ' Bildrunter
                        _console.Scroll_Down()
                        Return True
                    End If
                End If
            End If
        End If

        Return False
    End Function

    Private Sub StartForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        _console = New LibMultiPlug.Core.Console.MultiPlugConsole(Me)
        _console.SetVisibility(False)

        _console.RegisterCommandHandler(New LibMultiPlug.Core.Console.TransactionCommandHandler())

        LibUtils.log4net.Appender.VirtualConsoleAppender.SetConsole(_console)

    End Sub

    Private Sub ÜbersichtToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ÜbersichtToolStripMenuItem.Click
        Dim rf As New Forms.ReportForm
        rf.Show(MainDockPanel, 1)
    End Sub

    Private Sub ReportDefinierenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReportDefinierenToolStripMenuItem.Click
        Dim ref As New ReportEditForm
        ref.Show(MainDockPanel)
    End Sub
End Class
